import memberList from '@views/gfxy/common/memberList'
import { getAction, httpAction } from '@api/manage'
import moment from 'moment'

export const GfxyMemberListMixinTest = {
  components: {
    memberList
  },
  data() {
    return {
      title: '操作',
      visible: false,
      confirmLoading: false,
      model:{
        totalScore: 0.0,
        endTime: moment().format('YYYY'),
        startTime:moment().format('YYYY'),
      },
      memberListTables: [
        {
          date : moment().format('YYYY'),
          totalScore : 0,
          memberList:[],
          // state:false,
        },
      ],

      year:1,
      url:{
        memberList: {
          list: '/teaching/sxjd/queryMemberListByMainId'
        },
      }
    }
  },
  methods: {
    add(){
      this.edit(this.model)
    },

    edit(record){
      if (typeof this.editBefore === 'function') this.editBefore(record)
      this.visible = true
      this.$refs.form.resetFields()
      this.model = Object.assign({}, record)

      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(params)
      }
      this.$nextTick(() => {
      })
      if (typeof this.editAfter === 'function') this.editAfter(this.model)
    },

    requestSubTableData(params,success) {
      getAction(this.url.memberList.list, params).then(res => {
        let { result } = res
        let dataSource = []

        if (result) {
          if (Array.isArray(result)) {
            dataSource = result
          } else if (Array.isArray(result.records)) {
            dataSource = result.records
          }
        }
        console.log(dataSource)
        this.memberListTables = dataSource;

        typeof success === 'function' ? success(res) : ''
      }).finally(() => {
        // _that.memberListTable.loading = false
      })
    },
    classifyIntoFormData(allValues) {

      let result = Object.assign({}, this.model);
      result.memberListTables = this.memberListTables;
      return result;
    },


    validateError(msg){
      this.$message.error(msg)
    },

    request(formData) {
      let url = this.url.add, method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      httpAction(url, formData, method).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('ok')
          this.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    close() {
      this.visible = false
      this.$emit('close')
    },
    handleCancel() {
      this.close()
    },
    updateMemberList(){
      this.$nextTick(() => {
        this.$refs.memberListRef.computeScore()
      })
    },
    handleOk(){
      new Promise((resolve,reject) => {
        console.log("开始验证主表信息");
        this.$refs.form.validate((validat,obj) =>{
          validat ? resolve() : reject();
        })
      }).then(() => {
        console.log("主表信息校验成功，开始校验成员列表")
        var flag = false;
        for (var temp = 0;temp < this.memberListTables.length;temp++){
          if (!this.validateList()) {
            flag = true;
          }
        }
        return new Promise((resolve,reject) => {
            if (flag){
              reject();
            }else {
              resolve();
            }
          }
        ).then(() => {
          var Dflag = true;
          for (var temp = 0; temp < this.memberListTables.length;temp++){
            if (this.memberListTables[temp].memberList.length>0){

            }else {
              Dflag = false;
            }
          }
          return new Promise((resolve, reject) => {
            if(Dflag){
              resolve()
            } else {
              reject("请添加成员")
            }
          }).then(() => {
            console.log("成员列表校验成功， 开始校验工作量分配")
            return new Promise((resolve,reject) => {
              let result = 0;
              // this.memberListTables.forEach(item => {
              //   item.memberList.forEach(item => {
              //     result = result + item.totalScore
              //   })
              // })


              // for (let temp= 0;temp < this.memberListTables.length;temp++){
              //   for (let Temp = 0;Temp< this.memberListTables[temp].memberList.length;Temp++){
              //     console.log(this.memberListTables[temp].memberList[Temp].totalScore)
              //   }
              // }
              this.memberListTables.forEach(DItem=>{
                DItem.memberList.forEach(item=>{
                  console.log("123546")
                  result = result + item.score
                })
              })
              // result = this.$math.round(result);
              console.log(result, this.model.totalScore,"uqgjwfdqwbdcvbq")
              if (result > this.model.totalScore) {
                reject("积分总和超过总积分")
              } else {
                resolve();
              }
            }).then(() => {
              console.log("准备提交数据")
              this.memberListTables.forEach(Iitem => {
                Iitem.memberList.forEach(item => {
                  item.matchType = Iitem.memberList.matchType;
                })
              })
              let formData = this.classifyIntoFormData()
              // 发起请求
              console.log(formData,"提交的formData")
              console.log(this.memberListTables)

              return this.request(formData)

            }).catch((msg)=>{
              console.log("成员列表校验失败： " + msg)
              this.validateError(msg)
              return false;
            })
          }).catch((msg)=>{
            console.log("成员个数校验失败： " + msg)
            this.validateError(msg)
            return false;
          })
        }).catch((msg) => {
          console.log("成员列表校验失败： " + msg)
          this.validateError(msg)
          return false;
        })

      }).catch((obj) => {
        console.log("主表校验失败");
        this.validateError("请输入必填项");
        return false;
      })
    },
    validateList() {
      let result = true;
      for (let key in this.$refs.blocklist) {
        if(this.$refs.blocklist[key].length !=0 && typeof this.$refs.blocklist[key].validate === 'function'){
          this.$refs.blocklist[key].validate(valid => {
            result = result && valid;
            return;
          })
        }
      }
      return result;
    },
    getYear:function (){
      this.year = this.model.endTime - this.model.startTime + 1;
      console.log(this.year);
      this.setMemberScore()
    },
    // 选择年之后 关闭弹框
    panelStartChange: function(value){
      // const endOfYear = moment().endOf('year')
      this.model.startTime = value.format('YYYY');
      this.startDateOpen = false;
      this.getTotalScore();
      this.getYear();
      this.createArr();
    },
    // 选择年之后 关闭弹框
    panelEndChange: function(value){
      this.model.endTime = value.format('YYYY');
      this.endDateOpen = false;
      this.getTotalScore();
      this.getYear();
      this.createArr();

    },
    createArr: function () {
      this.memberListTables = [];
      this.getTotalScore()
      for (var temp = 0; temp < this.year; temp++){
        var Stemp =  this.model.totalScore / this.year;
        this.memberListTables.push({
          date : (parseInt(this.model.startTime)+temp)+'',
          totalScore : Stemp,
          memberList:[]
        })
      }
    },
    callback(val) {
      console.log(val);
    },

    setMemberScore: function () {
      console.log("开始算分")
      if (this.year === 1){
        console.log("一年")
        this.memberListTables[0].totalScore = this.model.totalScore;
      } else if (this.year  % 2 === 1){
        console.log("单数年算分")
        for (var  temp = 0; temp < this.memberListTables.length;temp++){
          this.memberListTables[temp].totalScore = this.getMemberScore()[0];
        }
        this.memberListTables[this.memberListTables.length-1].totalScore = this.getMemberScore()[1];
      }else {
        console.log("双数年算分")
        for (var  temp = 0; temp < this.memberListTables.length;temp++){
          this.memberListTables[temp].totalScore = this.model.totalScore / this.year;
          console.log(this.memberListTables[temp].totalScore,"memS")
        }
      }
    },

    getMemberScore: function () {
      var HScore = Math.round(this.model.totalScore / this.year)
      var FScore = this.model.totalScore - ((this.memberListTables.length-1) * HScore)
      return [HScore,FScore];
    }
  }
}